#include <string>
#include <iostream>

#include "ConnectionHandlerRelay.hpp"
#include "Logger.hpp"
#include "SSLWrapper.hpp"
#include "ConnectSocket.hpp"

ConnectionHandlerRelay::ConnectionHandlerRelay(SSL_CTX *globalcontext, const IP &relayhost, unsigned int relayport, unsigned int counter) 
	: ConnectionHandler(), globalContext(globalcontext), relayHost(relayhost), relayPort(relayport), counter(counter) 
{
}

void ConnectionHandlerRelay::handle() 
{
	//configure SSL for the server
	SSL* serverSsl = SSLWrapper::newConnection(globalContext);
	BIO* serverBio = SSLWrapper::sessionToChannel(connection->getFD(), serverSsl, false);
	LOGSTRM(Logger::INFO, "Client Certificate: " << SSLWrapper::sslPeerCertificateToString(serverSsl));

	//client connection
	ConnectSocket* clientSocket = new ConnectSocket(relayHost, relayPort);
	TCPConnection clientConnection = clientSocket->connect();

	SSL* clientSsl = SSLWrapper::newConnection(globalContext);
	BIO* clientBio = SSLWrapper::sessionToChannel(clientConnection.getFD(), clientSsl, true);
	LOGSTRM(Logger::INFO, "Server Certificate: " << SSLWrapper::sslPeerCertificateToString(clientSsl));

	//prepare filename
	std::stringstream stream;
	stream << "log" << counter << ".txt";

	SSLWrapper::connectChannels(*connection, serverBio, clientConnection, clientBio, stream.str());

	//shutdown SSL
	SSLWrapper::closeSession(clientSsl);
	SSLWrapper::closeSession(serverSsl);
}

ConnectionHandlerRelay::~ConnectionHandlerRelay()
{
}

